package com.yex.service.otc.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yex.base.WalletOper;
import com.yex.common.utils.DateUtil;
import com.yex.constant.Constant;
import com.yex.entity.WalletEntity;
import com.yex.service.SysConfigService;
import com.yex.service.WalletService;
import com.yex.utils.vo.*;
import com.yex.base.WalletOperEnum;
import com.yex.utils.JsonResultVo;
import com.yex.entity.otc.*;
import com.yex.entity.UserEntity;
import com.yex.base.ZeroResultException;
import com.yex.dao.otc.OtcEntrustDao;
import com.yex.service.UserService;
import com.yex.service.otc.*;
import com.yex.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

import static com.yex.utils.MathUtil.mul;

/**
 * <p>
 * otc 委托表 服务实现类
 * </p>
 *
 * @author Little Liu
 * @since 2018-05-02
 */
@Service
@Slf4j
public class OtcEntrustServiceImpl extends ServiceImpl<OtcEntrustDao, OtcEntrust> implements IOtcEntrustService {
    @Autowired
    private UserService fuserMapper;

    @Autowired
    private IOtcCoinService otcCoinService;

    @Autowired
    private WalletService otcWalletService;


    @Autowired
    private SysConfigService fsystemargsService;

    @Autowired
    private IOtcFeeConfigService otcFeeConfigService;


    @Override
    @Transactional
    public JsonResultVo saveOtcEntrust(OtcEntrust otcEntrust) {


        if (otcEntrust == null) {
            return new JsonResultVo(false, "参数不能为空", -1);
        }

        if (otcEntrust.getSeveral() == null && otcEntrust.getPrize() == null && otcEntrust.getCoinId() == null && otcEntrust.getUserId() == null && otcEntrust.getType() == null) {
            return new JsonResultVo(false, "参数不能为空", -1);
        }

        OtcCoin otcCoin = otcCoinService.selectById(otcEntrust.getCoinId());
        if (otcCoin == null) {
            return new JsonResultVo(false, "没有当前币种", -1);
        }

        //以指数价格自动获取
        if (otcEntrust.getAutoIndex() > AutoIndexEnum.NOT_INDEX) {
            if (otcEntrust.getFloating() == null) {
                return new JsonResultVo(false, "参数不能为空", -1);
            }

            if (MathUtil.sub(otcEntrust.getFloating(), new BigDecimal("100")).compareTo(otcCoin.getFloating()) == 1) {
                return new JsonResultVo(false, "填写价格只能在卯定价格的基础上下浮动" + Utils.rvZeroAndDot(otcCoin.getFloating().toPlainString()) + "%", -1);
            }

            if (MathUtil.sub(new BigDecimal("100"), otcEntrust.getFloating()).compareTo(otcCoin.getFloating()) == 1) {
                return new JsonResultVo(false, "填写价格只能在卯定价格的基础上下浮动" + Utils.rvZeroAndDot(otcCoin.getFloating().toPlainString()) + "%", -1);
            }


        } else {

            if (otcEntrust.getMarket() == null) {
                return new JsonResultVo(false, "参数不能为空", -1);
            }

            TickerVO tickerVO = null;
//            if (otcCoin.getCoinId().equals(Integer.valueOf(Constant.USDT_ID))) {
//                //tickerVO = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.COINMARKETCAP);
//            } else
                if (otcEntrust.getMarket() == AutoIndexEnum.OKCOIN) {
                tickerVO = AutoTradeUtils.getOkcoinTicker(otcCoin.getCoinName().toLowerCase() + "_usdt");
            } else if (otcEntrust.getMarket() == AutoIndexEnum.BINANCE) {
                tickerVO = AutoTradeUtils.getBinanceTicker(otcCoin.getCoinName().toUpperCase() + "USDT");
            } else if (otcEntrust.getMarket() == AutoIndexEnum.HUOBI) {
                tickerVO = AutoTradeUtils.getHuobiTicker(otcCoin.getCoinName().toLowerCase() + "usdt");
            } else if (otcEntrust.getMarket() == AutoIndexEnum.BITFINEX) {
                tickerVO = AutoTradeUtils.getBitfinexTicker(otcCoin.getCoinName().toUpperCase() + "USD");
            } else if (otcEntrust.getMarket() == AutoIndexEnum.COINMARKETCAP) {
                //tickerVO = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.COINMARKETCAP);
            } else {
                return new JsonResultVo(false, "参数不正确", -1);
            }

            tickerVO.setLast(mul(tickerVO.getLast(), new BigDecimal(fsystemargsService.getValue("exchange"))));
            BigDecimal floating = MathUtil.add(MathUtil.div(otcCoin.getFloating(), new BigDecimal("100")), new BigDecimal("1"));
            if (otcEntrust.getPrize().compareTo(mul(tickerVO.getLast(), floating)) == 1) {
                return new JsonResultVo(false, "填写价格只能在卯定价格的基础上下浮动" + Utils.rvZeroAndDot(otcCoin.getFloating().toPlainString()) + "%", -1);
            }

            floating = MathUtil.sub(new BigDecimal("1"), MathUtil.div(otcCoin.getFloating(), new BigDecimal("100")));
            if (otcEntrust.getPrize().compareTo(mul(tickerVO.getLast(), floating)) == -1) {
                return new JsonResultVo(false, "填写价格只能在卯定价格的基础上下浮动" + Utils.rvZeroAndDot(otcCoin.getFloating().toPlainString()) + "%", -1);
            }

        }


        //	判断当前是否已登录，如果未登录则跳转至登录页
        UserEntity fuser = fuserMapper.selectById(otcEntrust.getUserId());
        if (fuser == null) {
            return new JsonResultVo(false, "用户不存在", -1);
        }

//        //	判断当前是否已实名（即通过KYC1级）
//        if (fuser.getfValidateStatus() < 3) {
//            return new JsonResultVo(false, "请kyc1实名认证", null, 6001);
//        }
//
//        //	判断是否预留手机号，若没有即跳转至预留页面
//        if (fuser.getfTelephone() == null && fuser.getFisTelephoneBind() != 1) {
//            return new JsonResultVo(false, "没有绑定手机号", 6002);
//        }
//
//        FuserPayAccount fuserPayAccount= fuserPayAccountMapper.findFuserPayAccount(otcEntrust.getUserId());
//
//        if (fuserPayAccount==null) {
//            return new JsonResultVo(false, "请绑定支付方式", null, 6003);
//        }


        //	判断是否绑定银行卡或第三方支付方式
//        if (fuserPayAccountService.selectOpenCount(fuserPayAccount)<1) {
//            return new JsonResultVo(false, "请先开启一种支付方式", null, 6003);
//        }

/*
        if (fuser.getfTradePassword() == null) {
            return new JsonResultVo(false, "请先设置交易密码", null, 6004);
        }
*/
        OtcFeeConfig configByUserId = otcFeeConfigService.findOtcFeeConfigByUserId(otcEntrust.getUserId());
        if(configByUserId!=null){
            // 总金额
            if (otcEntrust.getType() == 0) {
                otcEntrust.setEnsureAmount(otcCoin.getEnsureAmount());
                otcEntrust.setRate(MathUtil.mul(configByUserId.getEntrustFee(),new BigDecimal("100")));
                otcEntrust.setFees(MathUtil.getBigDecimal(mul(otcEntrust.getSeveral(),configByUserId.getEntrustFee()), 8));
                otcEntrust.setAmount(MathUtil.mul(otcEntrust.getSeveral(), otcEntrust.getPrize()));
            } else {
                otcEntrust.setRate(MathUtil.mul(configByUserId.getEntrustFee(),new BigDecimal("100")));
                otcEntrust.setFees(MathUtil.getBigDecimal(mul(otcEntrust.getSeveral(),configByUserId.getEntrustFee()), 8));
                otcEntrust.setSeveral(MathUtil.getBigDecimal(MathUtil.sub(otcEntrust.getSeveral(), otcEntrust.getFees()), 8));
                otcEntrust.setAmount(MathUtil.getBigDecimal(mul(otcEntrust.getSeveral(), otcEntrust.getPrize()), 8));
            }
        }else {
            // 总金额
            if (otcEntrust.getType() == 0) {
                otcEntrust.setEnsureAmount(otcCoin.getEnsureAmount());
                otcEntrust.setRate(otcCoin.getFees());
                otcEntrust.setFees(MathUtil.getBigDecimal(mul(otcEntrust.getSeveral(), MathUtil.div(otcCoin.getFees(), new BigDecimal("100"))), 8));
                otcEntrust.setAmount(MathUtil.mul(otcEntrust.getSeveral(), otcEntrust.getPrize()));
            } else {
                otcEntrust.setRate(otcCoin.getFees());
                otcEntrust.setFees(MathUtil.getBigDecimal(mul(otcEntrust.getSeveral(), MathUtil.div(otcCoin.getFees(), new BigDecimal("100"))), 8));
                otcEntrust.setSeveral(MathUtil.getBigDecimal(MathUtil.sub(otcEntrust.getSeveral(), otcEntrust.getFees()), 8));
                otcEntrust.setAmount(MathUtil.getBigDecimal(mul(otcEntrust.getSeveral(), otcEntrust.getPrize()), 8));
            }
        }


        if (otcEntrust.getAmount().compareTo(new BigDecimal(LimitAmountEnum.TWO_THOUSAND + "")) == -1) {
            return new JsonResultVo(false, "最低委托金额为2000", -1);
        }

        //限额
        if (!Utils.hasLength(otcEntrust.getLimitAmount())) {


            if (otcEntrust.getAmount().compareTo(new BigDecimal(LimitAmountEnum.ONE_MILLION)) == 1) {
                return new JsonResultVo(false, "单笔限额应为200到100万之间", -1);
            }


            if (otcEntrust.getAmount().compareTo(new BigDecimal(LimitAmountEnum.TWO_THOUSAND)) == -1) {
                return new JsonResultVo(false, "最大限额不能小于2000", -1);
            }


            if (new BigDecimal("200").compareTo(otcEntrust.getAmount()) == 1) {
                return new JsonResultVo(false, "最小金额应小于最大限额", null, -1);
            }

            otcEntrust.setLimitAmount("200-" + Utils.rvZeroAndDot(otcEntrust.getAmount().toPlainString()));

        } else {
            String limitAmount = otcEntrust.getLimitAmount();
            String[] split = limitAmount.split("-");

            if (!Utils.hasLength(split[0])) {
                return new JsonResultVo(false, "参数不能为空", null, -1);
            }

            if (new BigDecimal(split[0]).compareTo(new BigDecimal(LimitAmountEnum.TWO_HUNDRED)) == -1) {
                return new JsonResultVo(false, "单笔限额应为200到100万之间", -1);
            }

            if (!Utils.hasLength(split[1])) {
                return new JsonResultVo(false, "参数不能为空", null, -1);
            }

            if (new BigDecimal(split[1]).compareTo(new BigDecimal(LimitAmountEnum.ONE_MILLION)) == 1) {
                return new JsonResultVo(false, "单笔限额应为200到100万之间", -1);
            }


            if (new BigDecimal(split[1]).compareTo(new BigDecimal(LimitAmountEnum.TWO_THOUSAND)) == -1) {
                return new JsonResultVo(false, "最大限额不能小于2000", -1);
            }


            if (new BigDecimal(split[0]).compareTo(new BigDecimal(split[1])) == 1) {
                return new JsonResultVo(false, "最小金额应小于最大限额", null, -1);
            }
        }

        otcEntrust.setCreateDate(new Date());
        otcEntrust.setModifyDate(new Date());
        otcEntrust.setStatus(StatusEnum.NORMAL);
        otcEntrust.setNumber(DateUtil.format(DateUtil.CURR_TIME, new Date()) + VerifyCodeUtils.generateVerifyCode(6, "0123456789"));

        String quota = fsystemargsService.getValue("quota");
        String[] quotas = quota.split("-");

        //	已认证==1
        if (fuser.getValidateStatus() ==1 ) {
            if (otcEntrust.getAmount().compareTo(new BigDecimal(quotas[0])) == 1) {
                return new JsonResultVo(false, "当前KYC等级最高交易金额为" + quotas[0] + "，前去认证更高等级", null, -1);
            }
        } else if (fuser.getValidateStatus() == 6) {
            if (otcEntrust.getAmount().compareTo(new BigDecimal(quotas[0])) == 1) {
                return new JsonResultVo(false, "当前KYC等级最高交易金额为" + quotas[0] + "，前去认证更高等级", null, -1);
            }
        } //	判断当前是否已实名（即通过KYC2级）
        else if (fuser.getValidateStatus() >= 5 && fuser.getValidateStatus() < 9) {
                if (otcEntrust.getAmount().compareTo(new BigDecimal(quotas[1])) == 1) {
                    return new JsonResultVo(false, "当前KYC等级最高交易金额为" + quotas[1] + "，前去认证更高等级", null, -1);
                }
            } else
                //	判断当前是否已实名（即通过KYC3级）
                if (fuser.getValidateStatus() == 9) {
                    if (otcEntrust.getAmount().compareTo(new BigDecimal(quotas[2])) == 1) {
                        return new JsonResultVo(false, "当前KYC等级最高交易金额为" + quotas[2], null, -1);
                    }
                }

        WalletEntity userCoinOtcWallet = otcWalletService.selectByUserId(otcEntrust.getUserId());
        if (userCoinOtcWallet == null) {
            return new JsonResultVo(false, "otc 钱包未生成", -1);
        }

        WalletEntity otcWallet = userCoinOtcWallet;

        //保证金 卖单不需要保证金
        if (otcEntrust.getType() == 0) {


            if (baseMapper.findEntrustTypeUser(otcEntrust.getCoinId(), otcEntrust.getUserId(), 0) > 0) {
                return new JsonResultVo(false, "已经存在委托订单", -1);
            }

            if (otcWallet.getTotal().compareTo(otcCoin.getEnsureAmount()) == -1) {
                return new JsonResultVo(false, "您当前保证金不足，最低需要" + Utils.rvZeroAndDot(otcCoin.getEnsureAmount().toPlainString()) + "个" + otcCoin.getCoinName(), -1);
            }

            //冻结
            WalletOper oper = new WalletOper();
//            oper.setTurnUserId(otcEntrust.getCoinId());
            oper.setUserId(otcEntrust.getUserId());
            oper.setAmount(otcCoin.getEnsureAmount());
            oper.setOper(WalletOperEnum.FROZEN);
            oper.setRemark("委托冻结保证金");

            JsonResultVo result = otcWalletService.updateWallet(oper);
            if (result.getCode() <= 0) {
                log.error("otcWalletMapper 失败 coinId：{}, userId:{},total:{},frozen:{}", otcEntrust.getCoinId(), otcEntrust.getUserId(), otcCoin.getEnsureAmount(), otcCoin.getEnsureAmount());
                throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
            }

        } else {

            if (baseMapper.findEntrustTypeUser(otcEntrust.getCoinId(), otcEntrust.getUserId(), 1) > 0) {
                return new JsonResultVo(false, "已经存在委托订单", -1);
            }

            if (otcWallet.getTotal().compareTo(MathUtil.add(otcEntrust.getSeveral(), otcEntrust.getFees())) == -1) {
                return new JsonResultVo(false, "您的可用余额不足，请重新下单", -1);
            }
            WalletOper oper = new WalletOper();
//            oper.setTurnUserId(otcEntrust.getCoinId());
            oper.setUserId(otcEntrust.getUserId());
            oper.setAmount(MathUtil.add(otcEntrust.getSeveral(), otcEntrust.getFees()));
            oper.setOper(WalletOperEnum.FROZEN);
            oper.setRemark("委托冻结数量");
            JsonResultVo result = otcWalletService.updateWallet(oper);

            if (result.getCode() <= 0) {
                log.error("otcWalletMapper 失败 coinId：{}, userId:{},total:{},frozen:{}", otcEntrust.getCoinId(), otcEntrust.getUserId(), otcEntrust.getSeveral(), otcEntrust.getSeveral());
                throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
            }
        }

        if (baseMapper.insert(otcEntrust) > 0) {
            return new JsonResultVo(true, "发布成功", 0);
        } else {
            throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
        }

    }

    @Override
    public JsonResultVo otcEntrustList(Integer coinId,Integer userId) {
        OtcCoin otcCoin = otcCoinService.selectById(coinId);
        if (otcCoin == null) {
            return new JsonResultVo(false, "没有当前币种", -1);
        }

        List<OtcEntrust> otcEntrustBuyList = baseMapper.otcEntrustBuyList(coinId);
        List<OtcEntrust> otcEntrustSellList = baseMapper.otcEntrustSellList(coinId);
        List<Map<String, Object>> otcEntrustBuyListMap = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("#,###");
        for (OtcEntrust otcEntrust : otcEntrustBuyList) {

            Map<String, Object> otcEntrustMap = new HashMap<>(16);
            UserEntity fuser = fuserMapper.selectById(otcEntrust.getUserId());
            String domain = Constant.Domain;
            if ("true".equals(Constant.IS_OPEN_OSS)) {
                domain = Constant.OSSURL;
            }

            otcEntrustMap.put("headImg", Utils.hasLength(fuser.getPhoto()) ? domain + fuser.getPhoto() : "");
            String realName = fuser.getRealName();

            otcEntrustMap.put("realName", Utils.hasLength(realName) ? realName.substring(0, realName.length() - 1) + "*" : "");
            //OtcOrderCount userOtcOrderCount = otcOrderCountMapper.findUserOtcOrderCount(otcEntrust.getUserId());
            boolean userOtcOrderCount=true;
            if (userOtcOrderCount) {
                otcEntrustMap.put("orderCount", 0);
                otcEntrustMap.put("complete", 0);
            } else {
//                int addNum = userOtcOrderCount.getSuccessOrderNum() + userOtcOrderCount.getSysNum();
//                otcEntrustMap.put("orderCount", addNum);
//                if (addNum == 0) {
//                    otcEntrustMap.put("complete", 0);
//                } else {
//                    BigDecimal divNum = MathUtil.div(new BigDecimal(userOtcOrderCount.getSuccessOrderNum() + ""), new BigDecimal(addNum + ""));
//                    otcEntrustMap.put("complete", MathUtil.getBigDecimalString(mul(MathUtil.getBigDecimal(divNum, 4), new BigDecimal("100")), 2));
//                }
            }

//            FuserPayAccount fuserPayAccount= fuserPayAccountMapper.findFuserPayAccount(otcEntrust.getUserId());
            boolean fuserPayAccount=true;
            if (fuserPayAccount) {
                otcEntrustMap.put("weChat", 0);
                otcEntrustMap.put("alipay", 0);
                otcEntrustMap.put("bankCard", 0);
            } else {
//                otcEntrustMap.put("weChat", fuserPayAccount.getfWenXinOpen());
//                otcEntrustMap.put("alipay", fuserPayAccount.getfAlipayOpen());
//                otcEntrustMap.put("bankCard", fuserPayAccount.getfBankAccountOpen());
            }
            String[] limitAmouts = otcEntrust.getLimitAmount().split("-");

            otcEntrustMap.put("limitAmount", df.format(new BigDecimal(limitAmouts[0])) + "-" + df.format(new BigDecimal(limitAmouts[1])));

            autoIndexTickerPrice(otcCoin.getId(), otcEntrust);
            otcEntrustMap.put("count", MathUtil.getBigDecimalString(MathUtil.sub(otcEntrust.getSeveral(), otcEntrust.getDealCount()), 4));
            BigDecimal dealAmount = mul(otcEntrust.getPrize(), otcEntrust.getDealCount());
            BigDecimal amount = mul(otcEntrust.getPrize(), otcEntrust.getSeveral());
            otcEntrustMap.put("amount", MathUtil.getBigDecimalString(MathUtil.sub(amount, dealAmount), 2));
            otcEntrustMap.put("prize", MathUtil.getBigDecimalString(otcEntrust.getPrize(), 2));

            otcEntrustMap.put("id", otcEntrust.getId());
//            String otcSession = redisService.getOtcSession(otcEntrust.getUserId());
            String otcSession="";
            otcEntrustMap.put("onLine", Utils.hasLength(otcSession) ? 1 : 0);

            otcEntrustMap.put("blacklist1", 0);
            otcEntrustMap.put("blacklist2", 0);
            if(userId!=null){
//                OtcBlacklist otcBlacklist1 = otcBlacklistService.selectOtcBlacklistByUserId(userId,otcEntrust.getUserId());
//                OtcBlacklist otcBlacklist2 = otcBlacklistService.selectOtcBlacklistByBlacklistUserId(userId,otcEntrust.getUserId());
//                if(otcBlacklist1!=null){
//                    otcEntrustMap.put("blacklist1", 1);
//                }
//                if(otcBlacklist2!=null){
//                    otcEntrustMap.put("blacklist2", 1);
//                }
            }

//            redisService.addOtcAutoPrice(otcEntrust.getUserId(), otcEntrust.getId(), otcEntrust.getPrize());

            otcEntrustBuyListMap.add(otcEntrustMap);
        }

        Collections.sort(otcEntrustBuyListMap, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                BigDecimal prize1 = new BigDecimal(String.valueOf(o1.get("prize")));
                BigDecimal prize2 = new BigDecimal(String.valueOf(o2.get("prize")));
                return prize2.compareTo(prize1);
            }
        });


        List<Map<String, Object>> otcEntrustSellListMap = new ArrayList<>();
        for (OtcEntrust otcEntrust : otcEntrustSellList) {

            Map<String, Object> otcEntrustMap = new HashMap<>(16);
            UserEntity fuser = fuserMapper.selectById(otcEntrust.getUserId());
            String domain = Constant.Domain;
            if ("true".equals(Constant.IS_OPEN_OSS)) {
                domain = Constant.OSSURL;
            }

            otcEntrustMap.put("headImg", Utils.hasLength(fuser.getPhoto()) ? domain + fuser.getPhoto() : "");

            String realName = fuser.getRealName();
            otcEntrustMap.put("realName", Utils.hasLength(realName) ? realName.substring(0, realName.length() - 1) + "*" : "");
//            OtcOrderCount userOtcOrderCount = otcOrderCountMapper.findUserOtcOrderCount(otcEntrust.getUserId());
            boolean userOtcOrderCount=true;
            if (userOtcOrderCount) {
                otcEntrustMap.put("complete", 0);
                otcEntrustMap.put("orderCount", 0);
            } else {
//                int addNum = userOtcOrderCount.getSuccessOrderNum() + userOtcOrderCount.getSysNum();
//                otcEntrustMap.put("orderCount", addNum);
//                if (addNum == 0) {
//                    otcEntrustMap.put("complete", 0);
//                } else {
//                    BigDecimal divNum = MathUtil.div(new BigDecimal(userOtcOrderCount.getSuccessOrderNum() + ""), new BigDecimal(addNum + ""));
//                    otcEntrustMap.put("complete", MathUtil.getBigDecimalString(mul(MathUtil.getBigDecimal(divNum, 4), new BigDecimal("100")), 2));
//                }
            }
//            FuserPayAccount fuserPayAccount = fuserPayAccountMapper.findFuserPayAccount(otcEntrust.getUserId());
            boolean fuserPayAccount=true;
            if (fuserPayAccount) {
                otcEntrustMap.put("weChat", 0);
                otcEntrustMap.put("bankCard", 0);
                otcEntrustMap.put("alipay", 0);
            } else {
//                otcEntrustMap.put("weChat", fuserPayAccount.getfWenXinOpen());
//                otcEntrustMap.put("alipay", fuserPayAccount.getfAlipayOpen());
//                otcEntrustMap.put("bankCard", fuserPayAccount.getfBankAccountOpen());
            }

            String[] limitAmouts = otcEntrust.getLimitAmount().split("-");

            otcEntrustMap.put("limitAmount", df.format(new BigDecimal(limitAmouts[0])) + "-" + df.format(new BigDecimal(limitAmouts[1])));

            autoIndexTickerPrice(otcCoin.getId(), otcEntrust);
            otcEntrustMap.put("prize", MathUtil.getBigDecimalString(otcEntrust.getPrize(), 2));
            otcEntrustMap.put("count", MathUtil.getBigDecimalString(MathUtil.sub(otcEntrust.getSeveral(), otcEntrust.getDealCount()), 4));

            BigDecimal dealAmount = mul(otcEntrust.getPrize(), otcEntrust.getDealCount());
            BigDecimal amount = mul(otcEntrust.getPrize(), otcEntrust.getSeveral());
            otcEntrustMap.put("amount", MathUtil.getBigDecimalString(MathUtil.sub(amount, dealAmount), 2));

            otcEntrustMap.put("id", otcEntrust.getId());
            String otcSession = "";//redisService.getOtcSession(otcEntrust.getUserId());
            otcEntrustMap.put("onLine", Utils.hasLength(otcSession) ? 1 : 0);

            otcEntrustMap.put("blacklist1", 0);
            otcEntrustMap.put("blacklist2", 0);
            if(userId!=null){
//                OtcBlacklist otcBlacklist1 = otcBlacklistService.selectOtcBlacklistByUserId(userId,otcEntrust.getUserId());
//                OtcBlacklist otcBlacklist2 = otcBlacklistService.selectOtcBlacklistByBlacklistUserId(userId,otcEntrust.getUserId());
//                if(otcBlacklist1!=null){
//                    otcEntrustMap.put("blacklist1", 1);
//                }
//                if(otcBlacklist2!=null){
//                    otcEntrustMap.put("blacklist2", 1);
//                }
            }

//            redisService.addOtcAutoPrice(otcEntrust.getUserId(), otcEntrust.getId(), otcEntrust.getPrize());

            otcEntrustSellListMap.add(otcEntrustMap);
        }

        Collections.sort(otcEntrustSellListMap, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                BigDecimal prize1 = new BigDecimal(String.valueOf(o1.get("prize")));
                BigDecimal prize2 = new BigDecimal(String.valueOf(o2.get("prize")));
                return prize1.compareTo(prize2);
            }
        });

        Map<String, List<Map<String, Object>>> map = new HashMap<>(16);
        map.put("otcEntrustBuyList", otcEntrustBuyListMap);
        map.put("otcEntrustSellList", otcEntrustSellListMap);

        return new JsonResultVo(true, "获取成功", map, 0);
    }


    @Override
    public JsonResultVo otcEntrustUserList(Integer coinId, Integer userId) {
        UserEntity fuser = fuserMapper.selectById(userId);
        if (fuser == null) {
            return new JsonResultVo(false, "用户不存在", -1);
        }

        List<OtcEntrust> otcEntrustBuyList = baseMapper.otcEntrustBuyUserList(coinId, userId);
        List<OtcEntrust> otcEntrustSellList = baseMapper.otcEntrustSellUserList(coinId, userId);

        List<Map<String, Object>> otcEntrustBuyListMap = new ArrayList<>();
        for (OtcEntrust otcEntrust : otcEntrustBuyList) {
            OtcCoin otcCoin = otcCoinService.selectById(otcEntrust.getCoinId());
            /*if (otcCoinService.selectById(coinId) == null) {
                return new JsonResultVo(false, "没有当前币种", -1);
            }*/
            //Fvirtualcointype fvirtualcointype = fvirtualcointypeService.selectById(otcCoin.getCoinId());

            Map<String, Object> otcEntrustMap = new HashMap<>(16);
            //otcEntrustMap.put("coinName", fvirtualcointype.getfShortName());
            otcEntrustMap.put("coinName", "");

            autoIndexTickerPrice(otcCoin.getId(), otcEntrust);
            otcEntrustMap.put("prize", MathUtil.getBigDecimalString(otcEntrust.getPrize(), 2));
            if (otcEntrust.getFinishCount().compareTo(BigDecimal.ZERO) == 0) {
                otcEntrustMap.put("avgPrize", 0);
            } else {
                otcEntrustMap.put("avgPrize", MathUtil.getBigDecimalString(MathUtil.div(otcEntrust.getFinishAmount(), otcEntrust.getFinishCount()), 2));
            }
            otcEntrustMap.put("count", MathUtil.getBigDecimalString(otcEntrust.getSeveral(), 4));
            otcEntrustMap.put("dealCount", MathUtil.getBigDecimalString(otcEntrust.getDealCount(), 4));
            otcEntrustMap.put("amount", MathUtil.getBigDecimalString(mul(otcEntrust.getPrize(), otcEntrust.getSeveral()), 2));
            otcEntrustMap.put("dealAmount", MathUtil.getBigDecimalString(mul(otcEntrust.getPrize(), otcEntrust.getDealCount()), 2));
            otcEntrustMap.put("time", DateUtil.format(DateUtil.DEFAULT_DATE_TIME, otcEntrust.getCreateDate()));
            otcEntrustMap.put("id", otcEntrust.getId());
            otcEntrustMap.put("status", otcEntrust.getStatus());
            otcEntrustBuyListMap.add(otcEntrustMap);
        }

        List<Map<String, Object>> otcEntrustSellListMap = new ArrayList<>();
        for (OtcEntrust otcEntrust : otcEntrustSellList) {
            OtcCoin otcCoin = otcCoinService.selectById(otcEntrust.getCoinId());
            /*if (otcCoinService.selectById(coinId) == null) {
                return new JsonResultVo(false, "没有当前币种", -1);
            }*/
            //Fvirtualcointype fvirtualcointype = fvirtualcointypeService.selectById(otcCoin.getCoinId());

            Map<String, Object> otcEntrustMap = new HashMap<>(16);
            //otcEntrustMap.put("coinName", fvirtualcointype.getfShortName());
            otcEntrustMap.put("coinName", "");

            autoIndexTickerPrice(otcCoin.getId(), otcEntrust);

            otcEntrustMap.put("prize", MathUtil.getBigDecimalString(otcEntrust.getPrize(), 2));
            if (otcEntrust.getFinishCount().compareTo(BigDecimal.ZERO) == 0) {
                otcEntrustMap.put("avgPrize", 0);
            } else {
                otcEntrustMap.put("avgPrize", MathUtil.getBigDecimalString(MathUtil.div(otcEntrust.getFinishAmount(), otcEntrust.getFinishCount()), 2));
            }
            otcEntrustMap.put("count", MathUtil.getBigDecimalString(otcEntrust.getSeveral(), 4));
            otcEntrustMap.put("dealCount", MathUtil.getBigDecimalString(otcEntrust.getDealCount(), 4));
            otcEntrustMap.put("amount", MathUtil.getBigDecimalString(mul(otcEntrust.getPrize(), otcEntrust.getSeveral()), 2));
            otcEntrustMap.put("dealAmount", MathUtil.getBigDecimalString(mul(otcEntrust.getPrize(), otcEntrust.getDealCount()), 2));
            otcEntrustMap.put("time", DateUtil.format(DateUtil.DEFAULT_DATE_TIME, otcEntrust.getCreateDate()));
            otcEntrustMap.put("status", otcEntrust.getStatus());
            otcEntrustMap.put("id", otcEntrust.getId());
            otcEntrustSellListMap.add(otcEntrustMap);
        }

        Map<String, List<Map<String, Object>>> map = new HashMap<>(16);
        map.put("otcEntrustBuyList", otcEntrustBuyListMap);
        map.put("otcEntrustSellList", otcEntrustSellListMap);

        return new JsonResultVo(true, "获取成功", map, 0);
    }

    @Override
    public JsonResultVo otcAppEntrustUserList(Integer userId) {
        UserEntity fuser = fuserMapper.selectById(userId);
        if (fuser == null) {
            return new JsonResultVo(false, "用户不存在", -1);
        }
        List<OtcEntrust> otcEntrustList = baseMapper.otcEntrustUserList(userId);
        List<Map<String, Object>> otcEntrustListMap = new ArrayList<>();
        for (OtcEntrust otcEntrust : otcEntrustList) {
            OtcCoin otcCoin = otcCoinService.selectById(otcEntrust.getCoinId());
            //Fvirtualcointype fvirtualcointype = fvirtualcointypeService.selectById(otcCoin.getCoinId());

            Map<String, Object> otcEntrustMap = new HashMap<>(16);
            //otcEntrustMap.put("coinName", fvirtualcointype.getfShortName());
            otcEntrustMap.put("coinName", "");

            autoIndexTickerPrice(otcCoin.getId(), otcEntrust);
            otcEntrustMap.put("prize", MathUtil.getBigDecimalString(otcEntrust.getPrize(), 2));
            if (otcEntrust.getFinishCount().compareTo(BigDecimal.ZERO) == 0) {
                otcEntrustMap.put("avgPrize", 0);
            } else {
                otcEntrustMap.put("avgPrize", MathUtil.getBigDecimalString(MathUtil.div(otcEntrust.getFinishAmount(), otcEntrust.getFinishCount()), 2));
            }
            otcEntrustMap.put("count", MathUtil.getBigDecimalString(otcEntrust.getSeveral(), 4));
            otcEntrustMap.put("dealCount", MathUtil.getBigDecimalString(otcEntrust.getDealCount(), 4));
            otcEntrustMap.put("amount", MathUtil.getBigDecimalString(mul(otcEntrust.getPrize(), otcEntrust.getSeveral()), 2));
            otcEntrustMap.put("dealAmount", MathUtil.getBigDecimalString(otcEntrust.getDealAmount(), 2));
            otcEntrustMap.put("time", DateUtil.format(DateUtil.DEFAULT_DATE_TIME, otcEntrust.getCreateDate()));
            otcEntrustMap.put("id", otcEntrust.getId());
            otcEntrustMap.put("status", otcEntrust.getStatus());
            otcEntrustMap.put("type", otcEntrust.getType());
            otcEntrustListMap.add(otcEntrustMap);
        }

        Map<String, List<Map<String, Object>>> map = new HashMap<>(16);
        map.put("otcEntrustList", otcEntrustListMap);

        return new JsonResultVo(true, "获取成功", map, 0);
    }

    @Override
    @Transactional
    public JsonResultVo suspendOtcEntrust(Integer entrustId, Integer userId) {
        OtcEntrust otcEntrust = baseMapper.selectById(entrustId);
        if (otcEntrust == null) {
            return new JsonResultVo(false, "没有当前委托订单", -1);
        }

        if (!otcEntrust.getUserId().equals(userId)) {
            return new JsonResultVo(false, "没有当前委托订单", -1);
        }

        if (otcEntrust.getStatus() == StatusEnum.THREE) {
            return new JsonResultVo(false, "已经取消了委托订单", -1);
        }

        if (otcEntrust.getStatus() == StatusEnum.DELETE) {
            return baseMapper.updateUnSuspendStatus(otcEntrust.getId()) > 0 ? new JsonResultVo(true, "启用成功", 0) : new JsonResultVo(false, "启用失败,请稍后再试!", -1);
        } else {
            return baseMapper.updateSuspendStatus(otcEntrust.getId()) > 0 ? new JsonResultVo(true, "暂停成功", 0) : new JsonResultVo(false, "暂停失败,请稍后再试!", -1);
        }

    }

    @Override
    @Transactional
    public JsonResultVo cancelOtcEntrust(Integer entrustId, Integer userId) {
        OtcEntrust otcEntrust = baseMapper.selectById(entrustId);
        if (otcEntrust == null) {
            return new JsonResultVo(false, "没有当前委托订单", -1);
        }

        if (!otcEntrust.getUserId().equals(userId)) {
            return new JsonResultVo(false, "没有当前委托订单", -1);
        }

        if (otcEntrust.getStatus() == StatusEnum.THREE) {
            return new JsonResultVo(false, "已经取消了委托订单", -1);
        }

        WalletEntity userCoinOtcWallet = otcWalletService.selectByUserId(otcEntrust.getUserId());
        if (userCoinOtcWallet == null) {
            return new JsonResultVo(false, "otc 钱包未生成", -1);
        }

        if (baseMapper.updateCancelStatus(otcEntrust.getId()) <= 0) {
            throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
        }

        if (otcEntrust.getType() == 0) {

            WalletOper oper = new WalletOper();
//            oper.setTurnUserId(otcEntrust.getCoinId());
            oper.setUserId(otcEntrust.getUserId());
            oper.setAmount(otcEntrust.getEnsureAmount());
            oper.setOper(WalletOperEnum.UNFRONZEN);
            oper.setRemark("取消了委托订单 冻结金额解冻");
            JsonResultVo result = otcWalletService.updateWallet(oper);
            if (result.getCode() <= 0) {
                log.error("otcWalletMapper 失败 coinId：{}, userId:{},total:{},frozen:{}", otcEntrust.getCoinId(), otcEntrust.getUserId(), otcEntrust.getEnsureAmount(), otcEntrust.getEnsureAmount());
                throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
            }
            return new JsonResultVo(true, "取消成功", 0);
        } else {
            BigDecimal subCount = MathUtil.sub(otcEntrust.getSeveral(), otcEntrust.getDealCount());
            BigDecimal subFees = MathUtil.sub(otcEntrust.getFees(), otcEntrust.getDealFees());
            BigDecimal addCount = MathUtil.getBigDecimal(MathUtil.add(subCount, subFees), 8);

            WalletOper oper = new WalletOper();
//            oper.setTurnUserId(otcEntrust.getCoinId());
            oper.setUserId(otcEntrust.getUserId());
            oper.setAmount(addCount);
            oper.setOper(WalletOperEnum.UNFRONZEN);
            oper.setRemark("取消了委托订单 剩余冻结金额解冻");
            JsonResultVo result = otcWalletService.updateWallet(oper);

            if (result.getCode() <= 0) {
                log.error("otcWalletMapper 失败 coinId：{}, userId:{},total:{},frozen:{}", otcEntrust.getCoinId(), otcEntrust.getUserId(), subCount, subCount);
                throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
            }
            return new JsonResultVo(true, "取消成功", 0);
        }
    }

    @Override
    @Transactional
    public JsonResultVo cancelAutoOtcEntrust(Integer entrustId, Integer userId) {
        OtcEntrust otcEntrust = baseMapper.selectById(entrustId);
        UserEntity fuser = fuserMapper.selectById(userId);
        if (otcEntrust.getSysAuto() == 0) {
            return new JsonResultVo(true, "不需要处理", 0);
        }

        String[] split = otcEntrust.getLimitAmount().split("-");
        autoIndexTickerPrice(otcEntrust.getCoinId(), otcEntrust);
        if (new BigDecimal(split[0]).compareTo(mul(MathUtil.sub(otcEntrust.getSeveral(), otcEntrust.getFinishCount()), otcEntrust.getPrize())) < 0) {
            return new JsonResultVo(true, "剩余金额大于最小限额", 0);
        }

        JsonResultVo jsonResultVo = cancelOtcEntrust(entrustId, userId);
        if (!jsonResultVo.isSuccess()) {
            throw new ZeroResultException(new JsonResultVo(false, "服务异常", -3));
        }

//        OtcCoin otcCoin = otcCoinService.selectById(otcEntrust.getCoinId());
//        String content = (String) redisService.getConfig("sysAutoSms");
//        content = content.replace("{coin_name}", otcCoin.getCoinName());
//        boolean flag = userSupport.SendOtcMessage(fuser, content, 0);
//        if (!flag) {
//            throw new ZeroResultException(new JsonResultVo(false, "服务异常", -3));
//        }
        return new JsonResultVo(true, "取消成功", 0);

    }

    @Override
    @Transactional
    public JsonResultVo updateAddDealCount(Integer entrustId, BigDecimal count, BigDecimal price) {
        OtcEntrust otcEntrust = baseMapper.selectById(entrustId);
        if (otcEntrust == null) {
            return new JsonResultVo(false, "没有当前委托订单", -1);
        }

        if (otcEntrust.getStatus() == StatusEnum.NORMAL) {
            if (otcEntrust.getSeveral().compareTo(MathUtil.add(otcEntrust.getDealCount(), count)) == -1) {
                return new JsonResultVo(false, "超过当前委托数量", -1);
            }

            String[] split = otcEntrust.getLimitAmount().split("-");
            BigDecimal subSeveral = MathUtil.sub(otcEntrust.getSeveral(), MathUtil.add(otcEntrust.getDealCount(), count));
            autoIndexTickerPrice(otcEntrust.getCoinId(), otcEntrust);
            if (otcEntrust.getSeveral().compareTo(MathUtil.add(otcEntrust.getDealCount(), count)) == 0) {
                if (baseMapper.updateFulfilStatus(otcEntrust.getId()) <= 0) {
                    throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
                }
            } else if (new BigDecimal(split[0]).compareTo(mul(subSeveral, otcEntrust.getPrize())) == 1) {

                if (baseMapper.updateSysAuto(otcEntrust.getId()) <= 0) {
                    throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
                }

                if (baseMapper.updateFulfilStatus(otcEntrust.getId()) <= 0) {
                    throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
                }
            }


            BigDecimal dealFees = BigDecimal.ZERO;
            if (otcEntrust.getType() == 0) {
                dealFees = MathUtil.getBigDecimal(mul(count, MathUtil.div(otcEntrust.getRate(), new BigDecimal("100"))), 8);
            } else {
//                BigDecimal div = MathUtil.div(count, otcEntrust.getSeveral());
//                dealFees = MathUtil.getBigDecimal(MathUtil.mul(otcEntrust.getFees(), div), 8);
                dealFees=MathUtil.getBigDecimal(MathUtil.mul(MathUtil.div(otcEntrust.getRate(), new BigDecimal("100")), count), 8);
            }

            Integer result = baseMapper.updateAddDealCount(entrustId, count, mul(price, count), dealFees);

            if (result <= 0) {
                log.error("updateAddDealCount 失败 entrustId：{}, count:{},price:{}", entrustId, count, mul(price, count));
                throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
            }
            return new JsonResultVo(true, "更新成功", 0);
        } else {
            return new JsonResultVo(false, "委托订单已暂定接单或者已经取消", -1);
        }
    }


    @Override
    @Transactional
    public JsonResultVo updateSubDealCount(Integer entrustId, BigDecimal count, BigDecimal price) {
        OtcEntrust otcEntrust = baseMapper.selectById(entrustId);
        if (otcEntrust == null) {
            return new JsonResultVo(false, "没有当前委托订单", -1);
        }

        if (otcEntrust.getStatus() == StatusEnum.FOUR) {

            if (otcEntrust.getSysAuto() > 0) {
                if (baseMapper.updateUnSysAuto(otcEntrust.getId()) <= 0) {
                    throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
                }
            }

            if (baseMapper.updateNormalStatus(otcEntrust.getId()) <= 0) {
                throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
            }
        }

        if (otcEntrust.getType() == 0) {
            BigDecimal dealFees = MathUtil.getBigDecimal(mul(count, MathUtil.div(otcEntrust.getRate(), new BigDecimal("100"))), 8);
            Integer result = baseMapper.updateSubDealCount(entrustId, count, mul(price, count), dealFees);
            if (result <= 0) {
                log.error("updateSubDealCount 失败 entrustId：{}, count:{},price:{}", entrustId, count, mul(price, count));
                throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
            }

            return new JsonResultVo(true, "更新成功", 0);
        } else {
//            BigDecimal div = MathUtil.div(count, otcEntrust.getSeveral());
//            BigDecimal dealFees = MathUtil.getBigDecimal(MathUtil.mul(otcEntrust.getFees(), div), 8);

            BigDecimal dealFees=MathUtil.getBigDecimal(MathUtil.mul(MathUtil.div(otcEntrust.getRate(), new BigDecimal("100")), count), 8);

            Integer result = baseMapper.updateSubDealCount(entrustId, count, mul(price, count), dealFees);

            if (result <= 0) {
                log.error("updateSubDealCount 失败 entrustId：{}, price:{}", entrustId, mul(price, count));
                throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
            }

            if (otcEntrust.getStatus() == StatusEnum.THREE) {
                count = MathUtil.add(count, dealFees);
                WalletOper oper = new WalletOper();
//                oper.setTurnUserId(otcEntrust.getCoinId());
                oper.setUserId(otcEntrust.getUserId());
                oper.setAmount(count);
                oper.setOper(WalletOperEnum.UNFRONZEN);
                oper.setRemark("取消了委托订单 剩余冻结金额解冻");
                JsonResultVo result1 = otcWalletService.updateWallet(oper);
                if (result1.getCode() <= 0) {
                    log.error("otcWalletMapper 失败 coinId：{}, userId:{},total:{},frozen:{}", otcEntrust.getCoinId(), otcEntrust.getUserId(), count, count);
                    throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
                }

            }
            return new JsonResultVo(true, "更新成功", 0);
        }


    }

    @Override
    public void autoIndexTickerPrice(Integer coinId, OtcEntrust otcEntrust) {
        OtcCoin otcCoin = otcCoinService.selectById(coinId);
        if (otcCoin == null) {
            log.error("otcCoinService 失败 coinId：{}", coinId);
            throw new ZeroResultException(new JsonResultVo(RespCode.NOT_MATH.getMsg()));
        }
        if (otcEntrust.getAutoIndex() > AutoIndexEnum.NOT_INDEX) {
            BigDecimal divFloating = MathUtil.div(otcEntrust.getFloating(), new BigDecimal("100"));
//            if (otcCoin.getCoinId().equals(Integer.valueOf(Constant.USDT_ID))) {
////                TickerVO otcLastPriceTicker = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.COINMARKETCAP);
////                if (otcLastPriceTicker != null) {
////                    otcEntrust.setPrize(mul(mul(otcLastPriceTicker.getLast(), divFloating), new BigDecimal(fsystemargsService.getValue("exchange"))));
////                }
//            } else
                if (otcEntrust.getAutoIndex() == AutoIndexEnum.OKCOIN) {
                TickerVO okcoinTicker = AutoTradeUtils.getOkcoinTicker(otcCoin.getCoinName().toLowerCase() + "_usdt");
                if (okcoinTicker != null) {
                    otcEntrust.setPrize(mul(mul(okcoinTicker.getLast(), divFloating), new BigDecimal(fsystemargsService.getValue("exchange"))));
                }
            } else if (otcEntrust.getAutoIndex() == AutoIndexEnum.BINANCE) {
                TickerVO binanceTicker = AutoTradeUtils.getBinanceTicker(otcCoin.getCoinName().toUpperCase() + "USDT");
                if (binanceTicker != null) {
                    otcEntrust.setPrize(mul(mul(binanceTicker.getLast(), divFloating), new BigDecimal(fsystemargsService.getValue("exchange"))));
                }
            } else if (otcEntrust.getAutoIndex() == AutoIndexEnum.HUOBI) {
                TickerVO huobiTicker = AutoTradeUtils.getHuobiTicker(otcCoin.getCoinName().toLowerCase() + "usdt");
                if (huobiTicker != null) {
                    otcEntrust.setPrize(mul(mul(huobiTicker.getLast(), divFloating), new BigDecimal(fsystemargsService.getValue("exchange"))));
                }
            } else if (otcEntrust.getAutoIndex() == AutoIndexEnum.BITFINEX) {
                TickerVO bitfinexTicker = AutoTradeUtils.getBitfinexTicker(otcCoin.getCoinName().toUpperCase() + "USD");
                if (bitfinexTicker != null) {
                    otcEntrust.setPrize(mul(mul(bitfinexTicker.getLast(), divFloating), new BigDecimal(fsystemargsService.getValue("exchange"))));
                }
            } else if (otcEntrust.getAutoIndex() == AutoIndexEnum.COINMARKETCAP) {
//                TickerVO otcLastPriceTicker = redisService.getOtcLastPriceTicker(otcCoin.getId(), AutoIndexEnum.COINMARKETCAP);
//                if (otcLastPriceTicker != null) {
//                    otcEntrust.setPrize(mul(mul(otcLastPriceTicker.getLast(), divFloating), new BigDecimal(fsystemargsService.getValue("exchange"))));
//                }
            }
        }
        otcEntrust.setPrize(MathUtil.getBigDecimal(otcEntrust.getPrize(), 2));
    }

    @Override
    @Transactional
    public JsonResultVo updateFinishCount(Integer entrustId, BigDecimal count, BigDecimal prize) {
        OtcEntrust otcEntrust = baseMapper.selectById(entrustId);
        if (otcEntrust == null) {
            return new JsonResultVo(false, "没有当前委托订单", -1);
        }
        if (otcEntrust.getType() == 0) {
            if (otcEntrust.getSeveral().compareTo(MathUtil.add(otcEntrust.getFinishCount(), count)) == 0) {
                WalletOper oper = new WalletOper();
//                oper.setTurnUserId(otcEntrust.getCoinId());
                oper.setUserId(otcEntrust.getUserId());
                oper.setAmount(otcEntrust.getEnsureAmount());
                oper.setOper(WalletOperEnum.UNFRONZEN);
                oper.setRemark("完成了委托订单 保证金金额解冻");
                JsonResultVo result1 = otcWalletService.updateWallet(oper);
                if (result1.getCode() <= 0) {
                    log.error("otcWalletMapper 失败 coinId：{}, userId:{},total:{},frozen:{}", otcEntrust.getCoinId(), otcEntrust.getUserId(), otcEntrust.getEnsureAmount(), otcEntrust.getEnsureAmount());
                    throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
                }
            }
            BigDecimal finishFees = MathUtil.getBigDecimal(mul(count, MathUtil.div(otcEntrust.getRate(), new BigDecimal("100"))), 8);
            Integer result = baseMapper.updateFinishCount(entrustId, count, mul(count, prize), finishFees);
            if (result <= 0) {
                log.error("updateFinishCount 失败 entrustId：{}, count:{}", entrustId, count);
                throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
            }
        } else {
//            BigDecimal div = MathUtil.div(count, otcEntrust.getSeveral());
//            BigDecimal finishFees = MathUtil.getBigDecimal(MathUtil.mul(otcEntrust.getFees(), div), 8);
            BigDecimal finishFees=MathUtil.getBigDecimal(MathUtil.mul(MathUtil.div(otcEntrust.getRate(), new BigDecimal("100")), count), 8);
            Integer result = baseMapper.updateFinishCount(entrustId, count, mul(count, prize), finishFees);
            if (result <= 0) {
                log.error("updateFinishCount 失败 entrustId：{}, count:{}", entrustId, count);
                throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
            }
            if (otcEntrust.getSeveral().compareTo(MathUtil.add(otcEntrust.getFinishCount(), count)) == 0) {
                WalletOper oper = new WalletOper();
//                oper.setTurnUserId(otcEntrust.getCoinId());
                oper.setUserId(otcEntrust.getUserId());
                oper.setAmount(MathUtil.sub(otcEntrust.getFees(), otcEntrust.getDealFees()));
                oper.setOper(WalletOperEnum.UNFRONZEN);
                oper.setRemark("完成了委托订单 退回剩余 冻结手续费");
                JsonResultVo result1 = otcWalletService.updateWallet(oper);
                if (result1.getCode() <= 0) {
                    log.error("otcWalletMapper 失败 coinId：{}, userId:{},total:{},frozen:{}", otcEntrust.getCoinId(), otcEntrust.getUserId(), otcEntrust.getEnsureAmount(), otcEntrust.getEnsureAmount());
                    throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
                }
            }
        }
        if (otcEntrust.getSeveral().compareTo(MathUtil.add(otcEntrust.getFinishCount(), count)) == 0) {
            Integer result1 = baseMapper.updateFinishStatus(entrustId, count);
            if (result1 <= 0) {
                log.error("updateFinishStatus 失败 entrustId：{}, count:{}", entrustId, count);
                throw new ZeroResultException(new JsonResultVo(RespCode.FAILURE.getMsg()));
            }
        }
        return new JsonResultVo(true, "更新成功", 0);
    }

    @Override
    public int queryNowOrder(int type, Integer userId) {
        Map<String, Object> paramap = new HashMap<>();
        paramap.put("type", type);
        paramap.put("userId", userId);
        return baseMapper.selectByMap(paramap).size();
    }
}
